<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="所属社区" prop="commId">
        <el-tree-select
          v-model="formData.commId"
          :data="communityTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择所属社区"
          value-key="id"
        />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备厂家" prop="factory">
            <el-select v-model="formData.factory" placeholder="请选择">
              <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.DOOR_FACTORY)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终端型号" prop="classType">
            <el-select v-model="formData.classType" placeholder="请选择">
              <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.DOOR_CLASS_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注信息" prop="equipName">
        <el-input v-model="formData.equipName" placeholder="请输入备注信息" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备MAC" prop="equipMac">
            <template v-if="formData.id != null">
              {{ formData.equipMac }}
            </template>
            <template v-else>
              <el-input v-model="formData.equipMac" placeholder="请输入设备MAC" />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备IP" prop="equipIp">
            <el-input v-model="formData.equipIp" placeholder="请输入设备IP" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="安装人员" prop="installMemberId">
          <el-input v-model="formData.installMemberName_" :readonly="true">
            <template #append>
              <el-button @click="openSelectMember">选择</el-button>
              <el-button @click="clearSelectMember">清空</el-button>
            </template>
          </el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <MemberUserSelect ref="openSelectMemberRef" @confirm-member-user="confirmMemberUser" />
</template>
<script setup lang="ts">
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { DoorControlApi, DoorControlVO } from '@/api/zwsj/doorcontrol'
import * as CommunityApi from '@/api/zwsj/community'
import MemberUserSelect from '@/views/zwsj/common/MemberUserSelect.vue'

/** 门禁设备 表单 */
defineOptions({ name: 'DoorControlForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  commId: undefined,
  factory: undefined,
  classType: undefined,
  equipName: undefined,
  equipMac: undefined,
  equipIp: undefined,
  positionType: undefined,
  installMemberId: undefined,
  installMemberName_: undefined,
  sort: undefined,
  onlineStatus: undefined,
  lastOnlineTime: undefined,
  externalLinkId: undefined,
})
const formRules = reactive({
  commId: [{ required: true, message: '社区不能为空', trigger: 'blur' }],
  factory: [{ required: true, message: '设备厂家不能为空', trigger: 'blur' }],
  classType: [{ required: true, message: '终端型号不能为空', trigger: 'blur' }],
  equipMac: [{ required: true, message: '设备MAC不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const communityTree = ref() // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number, commId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  //设置区域默认值
  formData.value.commId = commId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DoorControlApi.getDoorControl(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得社区树
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DoorControlApi.DoorControlVO
    if (formType.value === 'create') {
      await DoorControlApi.createDoorControl(data)
      message.success(t('common.createSuccess'))
    } else {
      await DoorControlApi.updateDoorControl(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    commId: undefined,
    classType: undefined,
    equipName: undefined,
    equipMac: undefined,
    equipIp: undefined,
    positionType: undefined,
    installMemberId: undefined,
    installMemberName_: undefined,
    sort: undefined,
    onlineStatus: undefined,
    lastOnlineTime: undefined,
    externalLinkId: undefined,
  }
  formRef.value?.resetFields()
}


// 选择安装人员
const openSelectMemberRef = ref()
const openSelectMember = async () => {
  openSelectMemberRef.value.open()
}

const confirmMemberUser = async (memberUser: any) => {
  formData.value.installMemberId = memberUser.id
  formData.value.installMemberName_ = memberUser.nickname
}

const clearSelectMember = async() => {
  formData.value.installMemberId = undefined
  formData.value.installMemberName_ = undefined
}

/** 获得区域树 */
const getTree = async () => {
  communityTree.value = []
  const data = await CommunityApi.listSimpleCommunitys()
  let community: Tree = { id: 0, name: '顶级区域', children: [] }
  community.children = handleTree(data)
  communityTree.value.push(community)
}
</script>